package com.panda.web.service.wechat.impl;

import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.panda.common.core.domain.model.LoginUser;
import com.panda.common.core.domain.model.WeChatLogin;
import com.panda.common.core.domain.model.WeChatLoginUser;
import com.panda.common.core.redis.RedisCache;
import com.panda.common.utils.SecurityUtils;
import com.panda.common.utils.StringUtils;
import com.panda.framework.web.service.SysLoginService;
import com.panda.web.domain.dto.ReportDTO;
import com.panda.web.domain.dto.TmobjDTO;
import com.panda.web.domain.dto.UserDTO;
import com.panda.web.domain.vo.CodeVO;
import com.panda.web.domain.vo.UserJob;
import com.panda.web.domain.vo.UserVO;
import com.panda.web.domain.vo.commons.ScoreVO;
import com.panda.web.entity.aims.CallAi;
import com.panda.web.entity.order.WechatOrder;
import com.panda.web.entity.product.OpenidProduct;
import com.panda.web.entity.wechat.WechatMajorWscp;
import com.panda.web.entity.wechat.WechatUser;
import com.panda.web.entity.wechatinfo.WechatUserinfo;
import com.panda.web.frameworkgzh.service.WeChatTokenService;
import com.panda.web.mapper.aims.CallAiMapper;
import com.panda.web.mapper.order.WechatOrderMapper;
import com.panda.web.mapper.product.OpenidProductMapper;
import com.panda.web.mapper.wechat.WechatMajorWscpMapper;
import com.panda.web.mapper.wechat.WechatUserMapper;
import com.panda.web.mapper.wechatinfo.WechatUserinfoMapper;
import com.panda.web.service.wechat.IWechatUserService;
import com.panda.web.utils.ReportPDFUtils;
import com.panda.web.utils.WeChatUtlis;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.springframework.beans.BeanUtils;

import java.text.SimpleDateFormat;
import java.util.*;

import lombok.extern.slf4j.Slf4j;
import com.panda.web.utils.pageutils.PageResult;
import org.springframework.transaction.annotation.Transactional;


/**
 * 公众号用户Service业务层处理
 *
 * @author cpanda
 * @date 2025-02-21
 */
@Slf4j
@Service
public class WechatUserServiceImpl extends ServiceImpl<WechatUserMapper, WechatUser> implements IWechatUserService {
    @Autowired
    private RedisCache redisCache;

    @Autowired
    WechatUserMapper wechatUserMapper;
    @Autowired
    WeChatUtlis weChatUtlis;

    @Value("${gzh.api.app-id}")
    private String appId; //AppID
    @Value("${gzh.api.app_secret}")
    private String appSecret; //AppSecret

    @Autowired
    ReportPDFUtils reportPDFUtils;
    @Autowired
    WeChatTokenService tokenService;
    @Autowired
    SysLoginService service;
    @Autowired
    WechatOrderMapper orderMapper;
    @Autowired
    WechatMajorWscpMapper wechatMajorWscpMapper;
    @Autowired
    OpenidProductMapper openidProductMapper;

    @Autowired
    CallAiMapper callAiMapper;
    @Autowired
    WechatUserinfoMapper userinfoMapper;

    /**
     * 根据code获取openId
     *
     * @param code
     * @return
     */
    @Override
    public CodeVO getOpenId(String code) throws Exception {

        // 构建请求URL
        StringBuilder builder = new StringBuilder("https://api.weixin.qq.com/sns/oauth2/access_token?appid=");
        builder.append(appId).append("&secret=").append(appSecret).append("&code=").append(code).append("&grant_type=authorization_code");
        String url = builder.toString();
        // 发送HTTP请求获取access_token和openid
        String response = weChatUtlis.httpGet(url);
        JSONObject parse = JSONObject.parse(response);
        String accessToken = parse.getString("access_token"); // 网页授权接口调用凭证
        String refreshToken = parse.getString("refresh_token"); // 网页授权接口调用凭证
        String openId = parse.getString("openid"); // 用户唯一标识
        CodeVO vo = new CodeVO();
        vo.setOpenId(openId);
        vo.setAccessToken(accessToken);
        vo.setRefreshToken(refreshToken);
        System.out.println(vo);
        System.out.println("openid+++++++---" + openId);
        System.out.println("accessToken:--------------" + accessToken);
        System.out.println("refreshToken:--------------" + refreshToken);
        System.out.println("code:--------------" + code);
        return vo;
    }


    /**
     * 分页查询
     *
     * @param dto
     * @param pageNum
     * @param pageSize
     * @return
     */
    @Override
    public PageResult<UserVO> PageList(UserDTO dto, Integer pageNum, Integer pageSize) {

        LoginUser loginUser = SecurityUtils.getLoginUser();
        log.info(loginUser.toString());
        log.info(loginUser.getOpenid());
        Page<WechatUser> page = new Page<>(pageNum, pageSize);
        QueryWrapper<WechatUser> queryWrapper = new QueryWrapper();//需要处理查询条件
        getQueryWrapper(dto, queryWrapper);//查询条件
        IPage<WechatUser> userIPage = wechatUserMapper.selectPage(page, queryWrapper);
        long total = userIPage.getTotal();
        List<WechatUser> records = userIPage.getRecords();
        List<UserVO> voList = userVoToList(records);//封装vo数据方法

        return new PageResult<>(voList, total, pageNum, pageSize);
    }

    //查询条件
    private static void getQueryWrapper(UserDTO dto, QueryWrapper<WechatUser> queryWrapper) {
        if (StringUtils.isNotNull(dto.getFamilyName())) {//姓氏
            queryWrapper.like("family_name", dto.getFamilyName());
        }
        if (StringUtils.isNotNull(dto.getNickname())) {//网名
            queryWrapper.like("nickname", dto.getNickname());
        }
        if (StringUtils.isNotNull(dto.getGraduateType())) {//毕业院校类别
            queryWrapper.like("graduate_type", dto.getGraduateType());
        }
        if (StringUtils.isNotNull(dto.getBackground())) {//学历
            queryWrapper.like("background", dto.getBackground());
        }
        if (StringUtils.isNotNull(dto.getCepingStatus())) {//是否网申测评 1是
            queryWrapper.eq("ceping_status", dto.getCepingStatus());
        }
        if (StringUtils.isNotNull(dto.getProjectExperience())) {

        }
        queryWrapper.orderByDesc("creation_time");
    }

    /**
     * 无分页查询
     *
     * @param dto
     * @return
     */
    @Override
    public List<UserVO> choiceList(UserDTO dto) {
        QueryWrapper<WechatUser> queryWrapper = new QueryWrapper();//需要处理查询条件
        //构建查询条件
        List<WechatUser> userList = wechatUserMapper.selectList(queryWrapper);
        List<UserVO> voList = userVoToList(userList);//封装vo数据方法
        return voList;
    }

    /**
     * 回显数据
     *
     * @param userId
     * @return
     */
    @Override
    public UserVO selectById(Long userId) {
        UserVO vo = new UserVO();
        WechatUser user = wechatUserMapper.selectById(userId);
        BeanUtils.copyProperties(user, vo);
        if (user.getBishi() != null && !user.getBishi().isEmpty()) {
            String bishi = user.getBishi();
            String[] answers = bishi.split(",");
            TmobjDTO tmobjDTO = new TmobjDTO();
            tmobjDTO.setAA(answers[0]);
            tmobjDTO.setAB(answers[1]);
            tmobjDTO.setAC(answers[2]);
            tmobjDTO.setAD(answers[3]);
            tmobjDTO.setAE(answers[4]);
            tmobjDTO.setAF(answers[5]);
            tmobjDTO.setAG(answers[6]);
            tmobjDTO.setAH(answers[7]);
            tmobjDTO.setAI(answers[8]);
            tmobjDTO.setAJ(answers[9]);
            vo.setTmObj(tmobjDTO);
        }
        List<WechatMajorWscp> wechatMajorWscpList = wechatMajorWscpMapper.findByOpenid(user.getOpenid());
        if (wechatMajorWscpList != null && !wechatMajorWscpList.isEmpty()) {
            vo.setWechatMajorWscpList(wechatMajorWscpList);
        } else {
            vo.setWechatMajorWscpList(new ArrayList<>());
        }
        return vo;
    }

    /**
     * 根据openid 回显
     *
     * @param openid
     * @return
     */
    @Override
    public UserVO getUserInfo(String openid) {
        UserVO vo = new UserVO();
        WechatUser user = wechatUserMapper.findByOpenId(openid);
        BeanUtils.copyProperties(user, vo);
        if (user.getBishi() != null && !user.getBishi().isEmpty()) {
            String bishi = user.getBishi();
            String[] answers = bishi.split(",");
            TmobjDTO tmobjDTO = new TmobjDTO();
            tmobjDTO.setAA(answers[0]);
            tmobjDTO.setAB(answers[1]);
            tmobjDTO.setAC(answers[2]);
            tmobjDTO.setAD(answers[3]);
            tmobjDTO.setAE(answers[4]);
            tmobjDTO.setAF(answers[5]);
            tmobjDTO.setAG(answers[6]);
            tmobjDTO.setAH(answers[7]);
            tmobjDTO.setAI(answers[8]);
            tmobjDTO.setAJ(answers[9]);
            vo.setTmObj(tmobjDTO);
        }
        List<WechatMajorWscp> wechatMajorWscpList = wechatMajorWscpMapper.findByOpenid(openid);
        if (wechatMajorWscpList != null && !wechatMajorWscpList.isEmpty()) {
            vo.setWechatMajorWscpList(wechatMajorWscpList);
        } else {
            vo.setWechatMajorWscpList(new ArrayList<>());
        }
        return vo;
    }

    /**
     * 修改
     *
     * @param dto
     * @return
     */
    @Override
    public int updateUser(UserDTO dto) {
        String openid = dto.getOpenid();
        WechatUser wechatUser = wechatUserMapper.findByOpenId(openid);
        wechatUser.setNickname(dto.getNickname());
        wechatUser.setHeadimgurl(dto.getHeadimgurl());
        wechatUserMapper.updateById(wechatUser);
        return 1;
    }

    /**
     * 绑定手机号
     *
     * @param dto
     * @return
     */
    @Override
    public int phone(UserDTO dto) {
        String openid = dto.getOpenid();
        String phoneNumber = dto.getPhoneNumber();
        WechatUser byPhoneNumber = wechatUserMapper.findByPhoneNumber(phoneNumber);
        if (byPhoneNumber != null) {
            throw new RuntimeException("该手机号已绑定用户无法绑定，请联系管理员");
        }
        WechatUser wechatUser = wechatUserMapper.findByOpenId(openid);
        wechatUser.setPhoneNumber(phoneNumber);
        wechatUserMapper.updateById(wechatUser);
        return 1;
    }

    /**
     * 获取用户的面试报告记录
     * @param openid
     * @return
     */
    @Override
    public List<CallAi> getUserAimsByOpenid(String openid) {
        List<CallAi>callAiList =  callAiMapper.findByOpenid(openid);
        return callAiList;
    }


    /**
     * 新增
     *
     * @param dto
     * @return
     */
    @Override
    public int insert(UserDTO dto) {
        WechatUser user = new WechatUser();
        BeanUtils.copyProperties(dto, user);
        wechatUserMapper.insert(user);
        return 1;
    }


    /**
     * 修改数据
     *
     * @param dto
     * @return
     */
    @Transactional
    @Override
    public synchronized ScoreVO updateUserById(UserDTO dto) {
        Date date = new Date(); // 定义日期格式
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String dateString = sdf.format(date); // 将 Date 转换为 String
        WechatUser wechatUser = wechatUserMapper.findByOpenId(dto.getOpenid());
        WechatUser user = new WechatUser();
        BeanUtils.copyProperties(dto, user);
        user.setUId(wechatUser.getUId());
        user.setAccessToken(wechatUser.getAccessToken());
        user.setCreationTime(wechatUser.getCreationTime());
        user.setCreateDate(wechatUser.getCreateDate());
        user.setNickname(wechatUser.getNickname());
        user.setHeadimgurl(wechatUser.getHeadimgurl());
        user.setUnionid(wechatUser.getUnionid());
        user.setOpenid(dto.getOpenid());
        user.setCreateUser(dto.getUId());
        user.setUpdateDate(date);
        user.setCreationTime(dateString);
        TmobjDTO tmObj = dto.getTmObj();
        StringBuilder bishi = tmObj.getBISHI(tmObj);
        String string = bishi.toString();
        user.setBishi(string); // Convert StringBuilder to String
        user.setCepingStatus("1"); //填写信息更新为1
        List<WechatMajorWscp> wechatMajorWscpList = dto.getWechatMajorWscpList();
        wechatMajorWscpMapper.deleteByOpenid(dto.getOpenid());//先删除 后添加
        if (wechatMajorWscpList != null && !wechatMajorWscpList.isEmpty()) {//添加专业
            user.setMajor(wechatMajorWscpList.get(0).getMajorName());
            for (WechatMajorWscp wechatMajorWscp : wechatMajorWscpList) {
                wechatMajorWscp.setOpenid(dto.getOpenid());
                wechatMajorWscpMapper.insert(wechatMajorWscp);
            }
        }
        wechatUserMapper.updateById(user);
        int score = weChatUtlis.calculateScore(user);//第一次分数
        int zZScore = calculateFinalScore(score);//系数城区
        //笔试固定答案
        List<String> gdDA = new ArrayList<>(Arrays.asList("B", "C", "A", "B", "C", "A", "A", "A", "D", "D"));
        String bishis = user.getBishi();
        String delimiter = ","; // 分隔符
        List<String> bishiList = convertStringToList(bishis, delimiter);
        int biShiScore = calculateScore(gdDA, bishiList);//笔试分数

        ScoreVO vo = new ScoreVO();//返回个人分数
        vo.setScore(zZScore);
        vo.setBSScore(biShiScore);
        return vo;
    }

    public static List<String> convertStringToList(String input, String delimiter) {
        if (input == null || input.isEmpty()) {
            throw new IllegalArgumentException("输入字符串不能为空");
        }
        return Arrays.asList(input.split(delimiter));
    }

    public static int calculateScore(List<String> answer, List<String> response) {
        if (answer.size() != response.size()) {
            throw new IllegalArgumentException("答案和答题结果的长度必须相同");
        }

        int score = 0;
        for (int i = 0; i < answer.size(); i++) {
            if (answer.get(i).equals(response.get(i))) {
                score += 10; // 每答对一题加10分
            }
        }
        return score;
    }

    /**
     * 删除数据(逻辑删除)
     *
     * @param ids
     * @return
     */
    @Override
    public int removeByUserIds(List<Long> ids) {
        for (Long id : ids) {
            WechatUser user = wechatUserMapper.selectById(id);
            wechatUserMapper.updateById(user);
        }
        return 1;
    }


    // 处理VO数据封装
    private List<UserVO> userVoToList(List<WechatUser> userList) {
        List<UserVO> voList = new ArrayList<>();
        if (userList.size() > 0 && !userList.isEmpty()) {
            for (WechatUser user : userList) {
                UserVO vo = new UserVO();
                BeanUtils.copyProperties(user, vo);
                List<WechatMajorWscp> wechatMajorWscpList = wechatMajorWscpMapper.findByOpenid(user.getOpenid());
                if (wechatMajorWscpList != null && !wechatMajorWscpList.isEmpty()) {
                    vo.setWechatMajorWscpList(wechatMajorWscpList);
                } else {
                    vo.setWechatMajorWscpList(new ArrayList<>());
                }
                List<OpenidProduct> products = openidProductMapper.findByOpenidList(user.getOpenid(), "0");
                if (products!=null&&!products.isEmpty()){
                    vo.setProductList(products);
                }else {
                    vo.setProductList(new ArrayList<>());
                }
                voList.add(vo);

            }
        }
        return voList;
    }


    /**
     * 生成报告
     *
     * @param dto
     * @return
     */
    @Transactional
    @Override
    public synchronized String getViewReport(ReportDTO dto) throws Exception {
        String openid = dto.getOpenid();
        if (!StringUtils.isNotEmpty(openid)) {
            throw new RuntimeException("空");
        }
        WechatUser wechatUser = wechatUserMapper.findByOpenId(openid);
        BeanUtils.copyProperties(wechatUser, dto);
        int score = weChatUtlis.calculateScore(wechatUser);
        int zuiZScore = calculateFinalScore(score);//系数乘区
        dto.setScore(zuiZScore);

        //固定答案
        List<String> gdDA = new ArrayList<>(Arrays.asList("B", "C", "A", "B", "C", "A", "A", "A", "D", "D"));
        String bishis = dto.getBishi();//个人答案
        String delimiter = ","; // 分隔符
        List<String> bishiList = convertStringToList(bishis, delimiter);//笔试分数
        int biShiScore = calculateScore(gdDA, bishiList);//笔试分数
        dto.setZZscore(biShiScore);

        List<String> employmentCompetence = weChatUtlis.getEmploymentCompetence(wechatUser);//就业竞争力
        List<String> proposal = weChatUtlis.getEmploymentPromotionProposal(wechatUser, zuiZScore);//就业提升建议
        dto.setEmploymentCompetence(employmentCompetence);
        dto.setProposal(proposal);
        //删除原报告 (生成新报告时，删除就报告，并删除服务器旧地址)原话收 ；
//        reportPDFUtils.deletedReportByOpenId(dto.getOpenid());
        //生成报告
        Map<String, String> dynamicPDF = reportPDFUtils.createDynamicPDF(dto);
        String path = reportPDFUtils.hBPDF(dynamicPDF, dto);//合并
        //更新个人分数，及报告地址
        wechatUser.setScore(zuiZScore);
        wechatUser.setBsScore(biShiScore);
        wechatUser.setReportUrl(path);
        wechatUser.setPdfFrequency(wechatUser.getPdfFrequency() + 1);//生成一次加1
        wechatUserMapper.updateById(wechatUser);
        return path;

    }

    /**
     * 根据openid 查询个人信息
     *
     * @param openid
     * @return
     */
    @Override
    public UserVO selectByOpenid(String openid) {
        UserVO vo = new UserVO();
        WechatUser wechatUser = wechatUserMapper.findByOpenId(openid);
        BeanUtils.copyProperties(wechatUser, vo);
        WechatUserinfo userinfo = userinfoMapper.findByOpenid(openid);
        if (userinfo==null){
            vo.setAiInterview(0);
        }else {
            vo.setAiInterview(userinfo.getAiInterview());
        }
        return vo;
    }

    /**
     * 查询个人购买列表
     *
     * @param openid
     * @return
     */
    @Override
    public List<UserJob> getOrderOpenid(String openid) {
        List<UserJob> userJobList = new ArrayList<>();
        WechatUser wechatUser = wechatUserMapper.findByOpenId(openid);
        List<WechatOrder> orderList = orderMapper.findByOpenid(openid);
        if (orderList != null && !orderList.isEmpty()) {
            for (WechatOrder order : orderList) {
                UserJob userJob = new UserJob();
                BeanUtils.copyProperties(order, userJob);
                userJob.setNickName(wechatUser.getNickname());
                userJobList.add(userJob);
            }
        }

        return userJobList;
    }


    public static int calculateFinalScore(int score) {
        double finalScore;

        if (score >= 0 && score <= 30) {
            finalScore = score * 2;
        } else if (score >= 31 && score <= 40) {
            finalScore = score * 1.8;
        } else if (score >= 41 && score <= 50) {
            finalScore = score * 1.6;
        } else if (score >= 51 && score <= 60) {
            finalScore = score * 1.4;
        } else if (score >= 61 && score <= 70) {
            finalScore = score * 1.2;
        } else if (score > 70) {
            finalScore = score * 1;
        } else {
            throw new IllegalArgumentException("分数不能为负数");
        }

        // 四舍五入并返回整数
        return (int) Math.round(finalScore);
    }

    /**
     * 获取token
     *
     * @param vo
     * @return
     */
    @Transactional
    @Override
    public synchronized WeChatLogin getToken(CodeVO vo) throws Exception {

        WeChatLogin wechatLogin = new WeChatLogin();
        WeChatLoginUser weChatLoginUser = new WeChatLoginUser();
        try {
            String openId = vo.getOpenId();
            if (!StringUtils.isNotNull(openId)) {
                throw new RuntimeException("openId是空,请重新授权");
            }
            String accessToken = vo.getAccessToken();
            //根据openId查询数据库是否存在
            WechatUser wechatUser = wechatUserMapper.findByOpenId(openId);
            if (wechatUser != null) {
                if (Objects.equals(wechatUser.getStatus(), "0")) {
                    String token = service.login(openId, "a12345678", null, null, null);
//                    // 生成token
//                  String token = weChatLogin(wechatUser.getOpenid());
                    BeanUtils.copyProperties(wechatUser, weChatLoginUser);
                    wechatLogin.setWeChatLoginUser(weChatLoginUser);
                    wechatLogin.setOpenId(openId);
                    wechatLogin.setToken(token);
                    return wechatLogin;
                } else {
                    throw new RuntimeException("账号异常");//此用户已拉黑
                }

            } else {
                log.info("openId++++++++：   " + openId);
                log.info("accessToken++++++++：   " + accessToken);
                log.info("refreshToken:" + vo.getRefreshToken());
                Date date = new Date();
                // 定义日期格式
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                String dateString = sdf.format(date); // 将 Date 转换为 String
                // 保存用户信息到数据库
                WechatUser user = new WechatUser();
                // 检查 access_token 是否有效
                boolean isTokenValid = isAccessTokenValid(accessToken, openId);
                if (!isTokenValid) {
                    // 如果 access_token 无效，尝试刷新
//                    String refreshToken = getRefreshTokenFromDatabase(openId); // 从数据库获取 refresh_token
                    if (vo.getRefreshToken() != null) {
                        JSONObject jsonResult = refreshAccessToken(vo.getRefreshToken()); // 刷新 access_token
                        if (jsonResult != null) {
                            accessToken = jsonResult.getString("access_token"); // 获取新的 access_token
                            String newRefreshToken = jsonResult.getString("refresh_token"); // 获取新的 refresh_toke
                            // 更新数据库中的 access_token 和 refresh_token
//                            updateTokenInDatabase(openId, accessToken, newRefreshToken);
                            user.setRefreshToken(newRefreshToken);
                        } else {
                            throw new RuntimeException("access_token 刷新失败，请重新授权");
                        }
                    } else {
                        throw new RuntimeException("refresh_token 不存在，请重新授权");
                    }
                }

                // 拉取用户信息(需scope为 snsapi_userinfo)
                StringBuilder builder1 = new StringBuilder("https://api.weixin.qq.com/sns/userinfo?access_token=");
                builder1.append(accessToken);
                builder1.append("&openid=");
                builder1.append(openId);
                builder1.append("&lang=zh_CN");

                // 发送HTTP请求获取用户信息
                String userInfo = weChatUtlis.httpGet(builder1.toString());

                JSONObject info = JSONObject.parse(userInfo);
                String nickname = info.getString("nickname");
                String sex = info.getString("sex"); // 1时是男性，值为2时是女性，值为0时是未知
                String headimgurl = info.getString("headimgurl");
                String unionid = info.getString("unionid");


                user.setAccessToken(accessToken);
                user.setRefreshToken(vo.getRefreshToken());
                user.setOpenid(openId);
                user.setOfficialOpenid(openId);
                user.setNickname(nickname);
                user.setSex(sex);
                user.setHeadimgurl(headimgurl);
                user.setUnionid(unionid);
                user.setCreateDate(date);
                user.setUpdateDate(date);
                user.setCreationTime(dateString);
                user.setTurnoverTime(dateString);
                wechatUserMapper.insert(user);
                WechatUser wechatUser1 = wechatUserMapper.findByOpenId(openId);
                // 生成token
                String token = service.login(openId, "a12345678", null, null, null);
                BeanUtils.copyProperties(wechatUser1, weChatLoginUser);
                wechatLogin.setWeChatLoginUser(weChatLoginUser);
                wechatLogin.setOpenId(openId);
                wechatLogin.setToken(token);
                return wechatLogin;
            }
        } catch (Exception e) {
            // 异常处理
            throw new Exception("获取微信用户信息失败", e);
        }
    }

//    public WeChatLogin getToken(CodeVO vo) throws Exception {
//        WeChatLogin wechatLogin = new WeChatLogin();
//        WeChatLoginUser weChatLoginUser = new WeChatLoginUser();
//        try {
//            String openId = vo.getOpenId();
//            if (!StringUtils.isNotNull(openId)) {
//                throw new RuntimeException("openId为空，请重新授权");
//            }
//
//            // 强制刷新 access_token（如果失效）
//            String accessToken = refreshAccessTokenIfNeeded(vo.getAccessToken(), vo.getRefreshToken(), openId);
//
//            // 拉取最新用户信息（每次登录都执行）
//            JSONObject userInfo = fetchWeChatUserInfo(accessToken, openId);
//            String nickname = userInfo.getString("nickname");
//            String headimgurl = userInfo.getString("headimgurl");
//            String sex = userInfo.getString("sex");
//            String unionid = userInfo.getString("unionid");
//
//            // 查询数据库用户是否存在
//            WechatUser wechatUser = wechatUserMapper.findByOpenId(openId);
//            Date now = new Date();
//            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
//            String currentTime = sdf.format(now);
//
//            if (wechatUser != null) {
//                // 老用户：更新信息
//                if (Objects.equals(wechatUser.getStatus(),"0")) {
//                    // 更新用户信息
//                    wechatUser.setNickname(nickname);
//                    wechatUser.setHeadimgurl(headimgurl);
////                    wechatUser.setSex(sex);
//                    wechatUser.setUnionid(unionid);
//                    wechatUser.setUpdateDate(now);
//                    wechatUser.setTurnoverTime(currentTime);
//                    wechatUser.setAccessToken(accessToken);
//                    wechatUser.setRefreshToken(vo.getRefreshToken());
//                    wechatUserMapper.updateById(wechatUser);
//                } else {
//                    throw new RuntimeException("账号异常"); // 用户被禁用
//                }
//            } else {
//                // 新用户：插入数据
//                WechatUser newUser = new WechatUser();
//                newUser.setOpenid(openId);
//                newUser.setNickname(nickname);
//                newUser.setHeadimgurl(headimgurl);
//                newUser.setSex(sex);
//                newUser.setUnionid(unionid);
//                newUser.setAccessToken(accessToken);
//                newUser.setRefreshToken(vo.getRefreshToken());
//                newUser.setCreateDate(now);
//                newUser.setUpdateDate(now);
//                newUser.setCreationTime(currentTime);
//                newUser.setTurnoverTime(currentTime);
//                newUser.setStatus("0"); // 默认正常状态
//                wechatUserMapper.insert(newUser);
//                wechatUser = newUser;
//            }
//
//            // 生成登录Token
//            String token = service.login(openId, "a12345678", null, null, null);
//            BeanUtils.copyProperties(wechatUser, weChatLoginUser);
//            wechatLogin.setWeChatLoginUser(weChatLoginUser);
//            wechatLogin.setOpenId(openId);
//            wechatLogin.setToken(token);
//            return wechatLogin;
//
//        } catch (Exception e) {
//            log.error("微信登录失败：", e);
//            throw new Exception("获取微信用户信息失败", e);
//        }
//    }

    // 辅助方法：刷新Token（如果失效）
    private String refreshAccessTokenIfNeeded(String accessToken, String refreshToken, String openId) throws Exception {
        if (!isAccessTokenValid(accessToken, openId)) {
            JSONObject refreshed = refreshAccessToken(refreshToken);
            if (refreshed != null) {
                return refreshed.getString("access_token");
            } else {
                throw new RuntimeException("Token刷新失败，请重新授权");
            }
        }
        return accessToken;
    }

    // 辅助方法：获取微信用户信息
    private JSONObject fetchWeChatUserInfo(String accessToken, String openId) throws Exception {
        String url = String.format(
                "https://api.weixin.qq.com/sns/userinfo?access_token=%s&openid=%s&lang=zh_CN",
                accessToken, openId
        );
        String response = weChatUtlis.httpGet(url);
        JSONObject userInfo = JSONObject.parseObject(response);
        log.info("微信API返回的用户信息：{}", userInfo.toJSONString()); // 添加此行
        if (userInfo.containsKey("errcode")) {
            throw new RuntimeException("获取用户信息失败：" + userInfo.getString("errmsg"));
        }
        return userInfo;
    }

    /**
     * 检查 access_token 是否有效
     */
    private boolean isAccessTokenValid(String accessToken, String openId) throws Exception {
        String url = String.format("https://api.weixin.qq.com/sns/auth?access_token=%s&openid=%s", accessToken, openId);
        String result = weChatUtlis.httpGet(url);
        JSONObject jsonResult = JSONObject.parseObject(result);
        return jsonResult.getIntValue("errcode") == 0; // errcode 为 0 表示有效
    }

    /**
     * 从数据库获取 refresh_token
     */
    private String getRefreshTokenFromDatabase(String openId) {
        WechatUser user = wechatUserMapper.findByOpenId(openId);
        return user != null ? user.getRefreshToken() : null;
    }

    /**
     * 刷新 access_token
     */
    private JSONObject refreshAccessToken(String refreshToken) throws Exception {
        String url = String.format("https://api.weixin.qq.com/sns/oauth2/refresh_token?appid=%s&grant_type=refresh_token&refresh_token=%s", appId, refreshToken);
        String result = weChatUtlis.httpGet(url);
        JSONObject jsonResult = JSONObject.parseObject(result);
        if (jsonResult.containsKey("errcode")) {
            return null; // 刷新失败
        }
        return jsonResult; // 返回刷新结果

    }

    /**
     * 更新数据库中的 access_token 和 refresh_token
     */
    private void updateTokenInDatabase(String openId, String accessToken, String refreshToken) {
        WechatUser wechatUser = wechatUserMapper.findByOpenId(openId);
        wechatUser.setOpenid(openId);
        wechatUser.setAccessToken(accessToken);
        wechatUser.setRefreshToken(refreshToken);
        wechatUserMapper.updateById(wechatUser);
    }

}